/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 沈明月
 * Date: 2022-11-07
 * Time: 13:50
 */
public class TestThree {
//二分查找:给定一个有序整型数组, 实现二分查找
    public static int binarySearch(int[] array, int n){
        int left =0;
        int right = array.length-1;
        boolean isFlg = false;
        int mid = (left+right)/2;

        while(left <= right){
            if(n >array[mid]){
                left = mid+1;
                mid = (left+right)/2;
            }
            if( n < array[mid]){
                right = mid-1;
                mid = (left+right)/2;
            }
            if(n == array[mid]){
                isFlg = true;
                break;
            }
        }
        if(isFlg == true){
            return mid;
        }else{
            return -1;
        }
    }
    //也可写作：
    public static int binarySearch2(int[] array,int key) {
        int left = 0;
        int right = array.length-1;
        while (left <= right) {
            int mid = (left+right)/2;
            if(array[mid] == key) {
                return mid;
            }else if(array[mid] < key) {
                left = mid+1;
            }else {
                right = mid-1;
            }
        }
        return -1;//代表没有找到这个数字
    }
    public static void main1(String[] args) {
        int [] array = new int [] {1,2,3,4,5};
        //确定要查找的数字：
        int n = 10;
        //进行查找：
        int ret = binarySearch(array,n);
        if(ret == -1){
            System.out.println("该数组中并无所查找的数");
        }else{
            System.out.println("被查找的数字在数组中的下标是"+ret);
        }
    }
}
